import { MessageBox } from "element-ui";

export function initPasteImg(Editor) {
  let doc = document.getElementById(Editor.id);
  doc.addEventListener("paste", function (event) {
    let items = (event.clipboardData || window.clipboardData).items;
    let file = null;
    if (items && items.length) {
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
    } else {
      console.log("当前浏览器不支持");
      return;
    }
    if (!file) {
      console.log("粘贴内容非图片");
      return;
    }
    uploadImg(file, Editor);
  });
  let dashboard = document.getElementById(Editor.id);
  dashboard.addEventListener("dragover", function (e) {
    e.preventDefault();
    e.stopPropagation();
  });
  dashboard.addEventListener("dragenter", function (e) {
    e.preventDefault();
    e.stopPropagation();
  });
  dashboard.addEventListener("drop", function (e) {
    e.preventDefault();
    e.stopPropagation();
    let files = this.files || e.dataTransfer.files;
    uploadImg(files[0], Editor);
  });
}

function uploadImg(file, Editor) {
  let formData = new FormData();
  let fileName = new Date().getTime() + "." + file.name.split(".").pop();
  formData.append("file", file, file.name);
  formData.append("token", sessionStorage.getItem("token"));
  $.ajax({
    type: "POST",
    url: Editor.settings.imageUploadURL, //获取我们配置的url
    data: formData,
    dateType: "json",
    processData: false,
    contentType: false,
    mimeType: "multipart/form-data",
    success: function (ret) {
      let res = JSON.parse(ret);
      if (res.code === "000000") {
        let url = res.data;
        Editor.insertValue("![图片alt](" + url + " ''图片title'')");
      } else {
        MessageBox.confirm("图片上传失败", "系统提示", {
          cancelButtonText: "取消",
          type: "warning",
        });
      }
    },
    error: function (err) {
      console.log("请求失败");
    },
  });
}
